<?php
/**
 * Controller_Auth
 *
 * Класс Controller_Auth отвечает за обработку авторизации и связанного с ней
 *
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 1.0
 */
class Controller_Auth extends Controller_Base {


  /**
	 * Выбор действия по URL
	 *
	 */
	public function action() {
	  Service_Debug::setDebug();
		//$this->addCrumb(Service_Translate::getText('Главная'), View_Base::getLanguageUrl(W_ABSPATH));
		$this->showRightColumn = true;
		$this->addCss('auth.css');
		$this->addCss('forms.css');
	  switch ($this->arrRequest[1]) {
			case 'sign_in':
				$this->actionSignIn();
				break;
			case 'sign_up':
				$this->getActionReg();
				break;
			case 'exit':case 'sign_out':
				$this->getActionExit();
				break;
			case 'recovery':
				$this->getActionRecovery();
				break;
      case 'approve':
				$this->getActionApprove(Service_Escape::absolutelyEscapeString($this->arrRequest[2]), Service_Function::absolutelyEscapeString($this->arrRequest[3]));
				break;
      case 'kaptcha':
				self::actionKcaptcha();
			  break;
			default:
				$this->setError(404);
				break;
		}
	}

	/**
	 * Действие - "Капча"
	 *
	 */
	public static function actionKcaptcha() {
	  Service_Debug::setDebug();
 	  $objSession = User_Session::instance();
	  $redirectFalse = true;
    $captcha = new Kcaptcha(135, 52);
  	$objSession->__set('keystring', $captcha->getKeyString());
	}

	/**
	 * Действие - "Вход в систему"
	 *
	 */
	public function actionSignIn() {
		Service_Debug::setDebug();
		$objSession = User_Session::instance();
		if ($objSession->isLoggedIn()) User_Session::moveTo(View_Base::getLanguageUrl(W_ABSPATH), Service_Translate::getText('Вы уже вошли'), 1);
		
		if (isset($_POST['User_User'])) {
			$objUser = new User_User($_POST['User_User']);
			$arrData = Service_Escape::requestDataArray('User_User');
			$loginOrEmail = $arrData['login_or_e_mail'];
	    $pass = $arrData['pass'];
	    $objAuth = new User_Auth($loginOrEmail, $pass);
	    try {
	    	if (!$objAuth->signIn()) throw new Exception($this->makeStandardError(Service_Translate::getText('Не удалось войти')));
			  User_Session::moveTo(View_Base::getLanguageUrl(W_ABSPATH));
		  } 
		  catch (Exception $e) {
			  $tempArr = array();
		  	$objUser->errorValidated('all', $tempArr, $e->getMessage());
			}
		}
		else $objUser = new User_User();
		$this->title = 'Вход на портал';
		$this->showRightColumn = false;
		//$this->addCrumb($this->title);
		$objViewAuth = new View_Auth();
		//$signUpLink = $objViewAuth->getLanguageUrl(W_ABSPATH . 'auth/sign_up/');
		//$this->pageHead =  '<a href="' . W_ABSPATH . 'auth/sign_up" style="float:right;">Регистрация</a>';

		$this->showHeader();
      $objViewAuth->getSignInForm($objUser);
		$this->showFooter();
	}
	
	/**
	 * Действие - "Регистрация"
	 *
	 */
	public function getActionReg() {
	  Service_Debug::setDebug();
		if (isset($_POST['User_User'])) {
			$objUser = new User_User($_POST['User_User']);
			$pass = $objUser->getField('pass');
			if ($objUser->save()) {
				// Оповещаем пользователя по электронной почте
			//	$objNotification = new User_Notification();
				//$objNotification->newAccount(Service_Amail::getUserEMail($objUser->tableFields), $objUser->getField('login'), $pass, $objUser->getField('approve_code'));
				$objAuth = new User_Auth();
				$objAuth->signInSuccess($objUser->id);
  			User_Session::moveTo(View_Base::getLanguageUrl(W_ABSPATH), Service_Translate::getText('Вы успешно зарегистрировались на сайте') , 1);
			}
		}
		else $objUser = new User_User();

		$this->title = 'Регистрация';
		$this->showRightColumn = false;
		$this->showLeftColumn = false;
		//$this->addCrumb($this->title);
		$objViewAuth = new View_Auth();
  		$signUpLink = $objViewAuth->getLanguageUrl(W_ABSPATH . 'auth/sign_in/');
		
    	$this->showHeader();
 			$objViewAuth->getRegForm($objUser);
		$this->showFooter();
	}



	/**
	 * Действие - "Выход"
	 *
	 */
	public function getActionExit() {
		$objSession = User_Session::instance();
		$objSession->logOut();
		//if (!empty($_SERVER['HTTP_REFERER'])) User_Session::moveTo($_SERVER['HTTP_REFERER']);
    //else 
    	User_Session::moveTo(View_Base::getLanguageUrl(W_ABSPATH));
	}

	/**
	 * Действие - "Подтверждение регистрации"
	 *
	 * @param $approveCode - код подтверждения регистрации
	 * @param $eMail - e-mail для подтверждения
	 */
	public function getActionApprove($approveCode, $eMail) {
		$objDb = Service_Database::instance();
		if (sizeof($approveCode) && sizeof($eMail)) {
    	$cntRows = $objDb->update('user', array('approved' => 1, 'approve_code' => ''), array('e_mail' => $eMail, 'approve_code' => $approveCode));
    	$objSession = User_Session::instance();
    	if (!$cntRows) $objSession->moveTo(View_Base::getLanguageUrl(W_ABSPATH), 'Wrong data. Registration confirmation error.', -1);
		}
		else $objSession->moveTo(View_Base::getLanguageUrl(W_ABSPATH), 'Wrong data. Registration confirmation error.', -1);
		$objSession->moveTo(View_Base::getLanguageUrl(W_ABSPATH), 'You have just successfully verified your registration at our website. To login please use the "Sign in" link at the top of the page', 1);
  }

	/**
	 * Действие - "Восстановление пароля"
	 *
	 */
	public function getActionRecovery() {
		if (isset($_POST['User_User'])) {
			$objUser = new User_User($_POST['User_User']);
			$objAuth = New User_Auth();
			$objAuth->setLoginOrEmail($objUser->getField('e_mail'));
			$objAuth->setKaptcha($objUser->getField('kaptcha'));
			if ($objAuth->recoveryPass()) User_Session::moveTo(View_Base::getLanguageUrl(W_ABSPATH. 'auth/sign_in/'), Service_Translate::getText('Новый пароль был выслал на ваш адрес электронной почты.'), 1);
		}
		
		else $objUser = new User_User();
		$this->title = Service_Translate::getText('Восстановление пароля');
		$this->showRightColumn = false;
		$this->pageHead = $this->title;
		$this->addCrumb($this->title);
		$objViewAuth = new View_Auth();
    $this->showHeader();
  		View_Auth::getRecoveryForm($objUser);
		$this->showFooter();
	}

}
?>